package com.kehao.leetcode.middle.tree_graph;

import org.junit.Test;

import java.util.HashMap;


public class KthSmallestSolution {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int kthSmallest(TreeNode root, int k) {
        int[] kthSmallestArray = new int[k];
        for (int i = 0; i < kthSmallestArray.length; i++) kthSmallestArray[i] = Integer.MAX_VALUE;
        kthSmallest(root,kthSmallestArray);
        return kthSmallestArray[k-1];
    }

    public void kthSmallest(TreeNode root, int[] kthSmallestArray) {
        if(root==null) return;
        for (int i = 0; i < kthSmallestArray.length; i++){
            if(root.val<kthSmallestArray[i]){
                for (int j = kthSmallestArray.length-1; j > i; j--) {
                    kthSmallestArray[j] = kthSmallestArray[j - 1];
                }
                kthSmallestArray[i] = root.val;
                break;
            }
        }
        kthSmallest(root.left,kthSmallestArray);
        kthSmallest(root.right,kthSmallestArray);
    }


    @Test
    public void test01(){
        Integer[] treeArray = {3,1,4,null,2};
        TreeNode root = buildTree(treeArray);
        int i = kthSmallest(root, 1);
        System.out.println(i);
    }

    @Test
    public void test02(){
        Integer[] treeArray = {5,3,6,2,4,null,null,1};
        TreeNode root = buildTree(treeArray);
        int i = kthSmallest(root, 3);
        System.out.println(i);
    }


    private TreeNode buildTree(Integer[] array) {
        HashMap<Integer,TreeNode> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            if(array[i]!=null){
                map.put(i,new TreeNode(array[i]));
            }
        }
        for (int i = 0; i < array.length; i++) {
            if(map.containsKey(i)){
                map.get(i).left = map.containsKey(i*2+1)? map.get(i*2+1):null;
                map.get(i).right = map.containsKey(i*2+2)?map.get(i*2+2):null;
            }
        }
        return  map.get(0);
    }
}
